package com.maodou.android.ui.page.account

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowLeft
import androidx.compose.material.icons.rounded.KeyboardArrowRight
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.maodou.android.R
import com.maodou.android.ui.page.CategoryKey
import com.maodou.android.ui.page.EditAccountKey
import com.maodou.android.viewmodel.account.AccountViewModel
import com.maodou.core.datastore.db.table.AccountEntry
import com.maodou.core.navigation.DialogStyle
import com.maodou.core.navigation.GlobalUiBus
import com.maodou.core.navigation.LocalDialogHandle
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.ActionBar
import com.maodou.core.ui.components.AppText
import com.maodou.core.ui.components.HSpacer
import com.maodou.core.ui.components.TitleAlignment
import com.maodou.core.ui.components.VSpacer
import com.maodou.core.ui.components.debouncedClickable
import com.maodou.core.ui.components.textfield.FormField
import com.maodou.core.ui.components.textfield.TextFieldType
import com.maodou.core.utils.permission.PermissionUtils
import com.maodou.core.utils.toastOnUi
import androidx.compose.material3.DropdownMenu
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import com.maodou.android.data.model.ProxyCheckResp
import com.maodou.android.ui.page.home.TagChip
import com.maodou.android.utils.PublicUtils.countryNameZh
import com.maodou.core.utils.JsonUtils
import com.maodou.core.utils.Logger

/**
 * @Author Xing
 * @CreateTime 2025年09月18日
 * @Description 单个账号添加或编辑
 */
@Composable
fun EditAccountScreen(
    key: EditAccountKey,
    viewModel: AccountViewModel = hiltViewModel(),
) {
    val context = LocalContext.current
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val navigationBarHeight = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
    // 本地表单状态
    var platform by remember { mutableStateOf( key.account?.platform ?: "Facebook") }
    var accountType by remember { mutableStateOf(key.account?.type ?:"个人号") }
    var accountId by remember { mutableStateOf(key.account?.accountID ?: "") }
    var nickname by remember { mutableStateOf(key.account?.nickname ?: "") }
    var phone by remember { mutableStateOf(key.account?.phone ?: "") }
    var password by remember { mutableStateOf(key.account?.password ?: "") }
    var twoFa by remember { mutableStateOf(key.account?.twoFa ?: "") }
    var email by remember { mutableStateOf(key.account?.email ?: "") }
    var emailPassword by remember { mutableStateOf(key.account?.emailPassword ?: "") }
    var ipCountry by remember { mutableStateOf(key.account?.ipCountry ?: "") }
    var cookie by remember { mutableStateOf(key.account?.cookie ?: "") }

    var proxyStr by remember { mutableStateOf("") }
    var proxyChannel by remember { mutableStateOf( key.account?.proxyChannel ?: "IP123") }
    var proxyType by remember { mutableStateOf(key.account?.proxyType ?: "Socks5") }
    var proxyHost by remember { mutableStateOf(key.account?.proxyHost ?: "") }
    var proxyPort by remember { mutableStateOf(key.account?.proxyPort ?: "") }
    var proxyAccount by remember { mutableStateOf(key.account?.proxyAccount ?: "") }
    var proxyPassword by remember { mutableStateOf(key.account?.proxyPassword ?: "") }

    val accountDetect = if(key.account?.proxyDetect?.isEmpty() == true) null else JsonUtils.fromJson<ProxyCheckResp>("${key.account?.proxyDetect}")
    var proxyIP by remember { mutableStateOf(accountDetect?.ip ?: "") }
    var proxyCountry by remember { mutableStateOf(accountDetect?.countryCode ?: "") }
    var proxyDetect by remember { mutableStateOf("") }

    Column {
        ActionBar(
            title = "账号管理",
            modifier = Modifier.fillMaxWidth(),
            navigationIcon = Icons.AutoMirrored.Outlined.KeyboardArrowLeft,
            onNavigationClick = {
                Navigator3.pop()
            },
            backgroundColor = Color.Transparent,
            contentColor = MaterialTheme.colorScheme.onSurface,
            titleAlignment = TitleAlignment.Center,
        )

        // 可滚动内容
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 16.dp, vertical = 12.dp)
        ) {
            val groupShape = RoundedCornerShape(16.dp)

            // 账号基本信息
            AppText(
                text = "基本信息",
                style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold),
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .shadow(elevation = 1.dp, shape = groupShape)
                    .clip(groupShape)
                    .background(Color.White)
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            GlobalUiBus.showPopup(
                                style = DialogStyle.Bottom,
                                dismissOnClickOutside = true,
                                dismissOnBackPress = false,
                                content = {
                                    val handle = LocalDialogHandle.current
                                    val items = arrayListOf("Facebook","Instagram")
                                    BottomWheelPicker(
                                        title = "平台",
                                        items = items,
                                        initialIndex = items.indexOf(platform).takeIf { it >= 0 } ?: 0,
                                        onConfirm = { index ->
                                            platform = items[index]
                                            handle?.close()
                                        },
                                        onCancel = {
                                            handle?.close()
                                        }
                                    )
                                }
                            )
                        }
                        .padding(horizontal = 16.dp, vertical = 14.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(
                        text = "平台",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.weight(1f))
                    AppText(text = platform, color = MaterialTheme.colorScheme.onSurfaceVariant)
                    HSpacer(4.dp)
                    Icon(
                        imageVector = Icons.Rounded.KeyboardArrowRight,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant, modifier = Modifier.padding(horizontal = 16.dp))
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            GlobalUiBus.showPopup(
                                style = DialogStyle.Bottom,
                                dismissOnClickOutside = true,
                                dismissOnBackPress = false,
                                content = {
                                    val handle = LocalDialogHandle.current
                                    val items = arrayListOf("个人号","企业号")
                                    BottomWheelPicker(
                                        title = "类型",
                                        items = items,
                                        initialIndex = items.indexOf(accountType).takeIf { it >= 0 } ?: 0,
                                        onConfirm = { index ->
                                            accountType = items[index]
                                            handle?.close()
                                        },
                                        onCancel = { handle?.close() },
                                        bottomActionText = "去添加",
                                        onBottomAction = {
                                            Navigator3.navigate(CategoryKey)
                                            handle?.close()
                                        },
                                        bottomNote = "注：平台提供自定义账号分类，方便使用者管理账号"
                                    )
                                }
                            )
                        }
                        .padding(horizontal = 16.dp, vertical = 14.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(
                        text = "类型",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.weight(1f))
                    AppText(text = accountType, color = MaterialTheme.colorScheme.onSurfaceVariant)
                    HSpacer(4.dp)
                    Icon(
                        imageVector = Icons.Rounded.KeyboardArrowRight,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            VSpacer(16.dp)

            // 账号鉴定信息
            AppText(
                text = "账号信息",
                style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold),
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .shadow(elevation = 1.dp, shape = groupShape)
                    .clip(groupShape)
                    .background(Color.White)
                    .padding(horizontal = 12.dp, vertical = 4.dp)
            ) {
                // 账号ID
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 6.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = buildAnnotatedString {
                            append("账号ID")
                            withStyle(SpanStyle(color = MaterialTheme.colorScheme.error)) { append("*") }
                        },
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp)
                    )
                    FormField(
                        value = accountId,
                        onValueChange = { accountId = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        maxLength = 50,
                        enabled = key.account?.accountID == null,
                        borderless = true
                    )
                    HSpacer(6.dp)
                    if(key.account?.accountID == null) Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "粘贴账号ID",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                val pasted = pasteText(context)
                                if (pasted != null) {
                                    accountId = pasted
                                    context.toastOnUi("已粘贴到账号ID")
                                } else {
                                    context.toastOnUi("剪贴板为空或非文本")
                                }
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 昵称/备注
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "昵称/备注",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp))
                    FormField(
                        value = nickname,
                        onValueChange = { nickname = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        maxLength = 50,
                        borderless = true
                    )
                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "复制昵称/备注",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    nickname = it
                                    context.toastOnUi("已粘贴到昵称/备注")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 手机号
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "手机号",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                        ,modifier = Modifier.width(80.dp))
                    FormField(
                        value = phone,
                        onValueChange = { phone = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        maxLength = 20,
                        type = TextFieldType.Text,
                        borderless = true
                    )
                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "复制手机号",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    phone = it
                                    context.toastOnUi("已粘贴到手机号")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 密码
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "密码",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp))
                    FormField(
                        value = password,
                        onValueChange = { password = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        type = TextFieldType.Text,
                        maxLength = 100,
                        borderless = true
                    )
                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "复制密码",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    password = it
                                    context.toastOnUi("已粘贴到密码")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 2FA
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "2FA",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp))
                    FormField(
                        value = twoFa,
                        onValueChange = { twoFa = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        maxLength = 50,
                        borderless = true
                    )
                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "复制2FA",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    twoFa = it
                                    context.toastOnUi("已粘贴到 2FA")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 邮箱
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "邮箱",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp))
                    FormField(
                        value = email,
                        onValueChange = { email = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        maxLength = 100,
                        type = TextFieldType.Email,
                        borderless = true
                    )
                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "复制邮箱",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    email = it
                                    context.toastOnUi("已粘贴到邮箱")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 邮箱密码（带复制）
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "邮箱密码",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp))
                    FormField(
                        value = emailPassword,
                        onValueChange = { emailPassword = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        type = TextFieldType.Text,
                        maxLength = 100,
                        borderless = true
                    )
                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "复制邮箱密码",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    emailPassword = it
                                    context.toastOnUi("已粘贴到邮箱密码")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // IP/国家
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "IP/国家",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp))
                    FormField(
                        value = ipCountry,
                        onValueChange = { ipCountry = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        borderless = true
                    )
                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "IP/国家",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    ipCountry = it
                                    context.toastOnUi("已粘贴到IP/国家")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // cookie
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.Top
                ) {
                    AppText(text = "Cookie",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp).padding(top = 22.dp))
                    FormField(
                        value = cookie,
                        onValueChange = { cookie = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "长按粘贴",
                        borderless = true
                    )
                }

                VSpacer(12.dp)
            }

            VSpacer(16.dp)

            // 代理信息
            Row(
                modifier = Modifier.padding(bottom = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                AppText(
                    text = "自定义代理",
                    style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold),
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
                AppText(
                    text = "(不设置则跟随系统)",
                    style = MaterialTheme.typography.bodySmall.copy(fontSize = 10.sp),
                    color = MaterialTheme.colorScheme.onSurfaceVariant,

                )
                Spacer(modifier = Modifier.weight(1f))
                val isEdit = !uiState.isCheckProxy && proxyChannel.isNotEmpty() && proxyType.isNotEmpty() && proxyHost.isNotEmpty() && proxyPort.isNotEmpty()
                Button(
                    onClick = {
                        PermissionUtils.requestVpnServicePermissions {
                            //todo 获取vpn权限后开始检测
                            viewModel.proxyCheck(
                                channel = proxyChannel,
                                protocol = proxyType,
                                host = proxyHost,
                                port = proxyPort,
                                username = proxyAccount,
                                password = proxyPassword,
                            ){
                                val checkResp = JsonUtils.fromJson<ProxyCheckResp>(it)
                                proxyIP = checkResp?.ip ?: ""
                                proxyCountry = checkResp?.countryCode ?: ""
                                proxyDetect = it
                                Logger.d("解析结果=${proxyDetect}")
                            }
                        }
                    },
                    border = BorderStroke(1.dp, color = if(isEdit) MaterialTheme.colorScheme.primary else Color.Transparent),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color.White,
                        contentColor = Color.White
                    ),

                    contentPadding = PaddingValues(1.dp),
                    enabled = isEdit,
                    modifier = Modifier
                        .height(20.dp)
                        .width(56.dp),
                    shape = RoundedCornerShape(4.dp)
                ) {
                    if (uiState.isCheckProxy) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(12.dp),
                            strokeWidth = 2.dp,
                            color = MaterialTheme.colorScheme.onSecondary
                        )
                        Text(
                            text = "检测中...",
                            textAlign = TextAlign.Center,
                            color = MaterialTheme.colorScheme.onSecondary,
                            fontSize = 10.sp
                        )
                    } else Text(text = "代理检测", textAlign = TextAlign.Center, fontSize = 10.sp, lineHeight = 11.sp, color = if(isEdit) MaterialTheme.colorScheme.primary else Color.White)
                }
            }
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .shadow(elevation = 1.dp, shape = groupShape)
                    .clip(groupShape)
                    .background(Color.White)
            ) {
                FormField(
                    value = proxyStr,
                    onValueChange = { proxyStr = it },
                    label = "",
                    modifier = Modifier.fillMaxWidth(),
                    placeholder = "「粘贴识别」或输入文本支持格式:\n协议://用户名:密码@主机:端口号\n\n如遇解析失败请手动收入以下信息",
                    maxLength = 400,
                    type = TextFieldType.Multiline,
                    textStyle = TextStyle(
                        fontSize = 14.sp,
                        lineHeight = 18.sp,
                        color = Color.Black
                    ),
                    borderless = true,
                )
                Row(
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 14.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    if(proxyCountry.isNotEmpty()) TagChip(countryNameZh(proxyCountry))
                    HSpacer(6.dp)
                    if(proxyIP.isNotEmpty()) TagChip(proxyIP)
                    Spacer(modifier = Modifier.weight(1f))
                    Box(
                        modifier = Modifier
                            .background(color = Color(0xffFF758A), shape = RoundedCornerShape(20.dp))
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    proxyStr = it
                                    context.toastOnUi("已粘贴")
                                    viewModel.proxyFormatStr(proxyStr) { proxy ->
                                        proxy.proxyType?.let { proxyType = it }
                                        proxy.proxyHost?.let { proxyHost = it }
                                        proxy.proxyPort?.let { proxyPort = it }
                                        proxy.proxyAccount?.let { proxyAccount = it }
                                        proxy.proxyPassword?.let { proxyPassword = it }
                                    }
                                } ?: context.toastOnUi("剪贴板为空或非文本")

                            }
                    ) {
                        Text("粘贴并识别", color = Color.White, fontSize = 11.sp, modifier = Modifier.padding(horizontal = 10.dp))
                    }
                }
            }
            VSpacer(12.dp)
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .shadow(elevation = 1.dp, shape = groupShape)
                    .clip(groupShape)
                    .background(Color.White)
                    .padding(horizontal = 12.dp, vertical = 4.dp)
            ) {
                // IP查询渠道
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            GlobalUiBus.showPopup(
                                style = DialogStyle.Bottom,
                                dismissOnClickOutside = true,
                                dismissOnBackPress = false,
                                content = {
                                    val handle = LocalDialogHandle.current
                                    val items = arrayListOf("IP123","IPInfo")
                                    BottomWheelPicker(
                                        title = "IP渠道",
                                        items = items,
                                        initialIndex = items.indexOf(platform).takeIf { it >= 0 } ?: 0,
                                        onConfirm = { index ->
                                            proxyChannel = items[index]
                                            handle?.close()
                                        },
                                        onCancel = {
                                            handle?.close()
                                        }
                                    )
                                }
                            )
                        }
                        .padding(vertical = 14.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(
                        text = "IP查询渠道",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(96.dp)
                    )
                    AppText(text = proxyChannel ?: "请选择", color = MaterialTheme.colorScheme.onSurfaceVariant)
                    Spacer(modifier = Modifier.weight(1f))

                    if(!proxyChannel.isNullOrEmpty()){
                        Row (
                            modifier = Modifier.debouncedClickable {
                                proxyChannel = "IP123"
                                proxyType = "Socks5"
                                proxyHost = ""
                                proxyPort = ""
                                proxyAccount = ""
                                proxyPassword = ""
                            }.border(1.dp, color = Color(0xff999999), shape = RoundedCornerShape(4.dp)),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.Center
                        ){
                            Text(text = "清空",
                                textAlign = TextAlign.Center,
                                color = Color(0xff999999),
                                fontSize = 10.sp,
                                lineHeight = 10.sp,
                                modifier = Modifier.padding(horizontal = 6.dp, vertical = 1.dp)
                            )
                        }
                    }
                    HSpacer(6.dp)
                    InfoPopIcon(
                        text = "1.浏览器窗口的工作台页面展示的PP相关信息，将使用您选择的IP查询渠道进行查询与展示!\n2.不同的IP查询渠道，可能会存在一定的检测结果差异!若代理检测结果与实际信息不符，可以调整IP查询渠道以确保检测结果的准确性!\n3.若该窗口的指纹设置中，勾选了基于IP生成:语言、界面语言、时区、地理位置，请确保选择的IP查询渠道的检测结果与实际信息相符，否则会导致上述几处自动生成后产生误差!",
                        iconSize = 16.dp
                    )
                    Icon(
                        imageVector = Icons.Rounded.KeyboardArrowRight,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
                // 代理类型
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            GlobalUiBus.showPopup(
                                style = DialogStyle.Bottom,
                                dismissOnClickOutside = true,
                                dismissOnBackPress = false,
                                content = {
                                    val handle = LocalDialogHandle.current
                                    val items = arrayListOf("Socks5", "HTTP")
                                    BottomWheelPicker(
                                        title = "代理类型",
                                        items = items,
                                        initialIndex = items.indexOf(platform).takeIf { it >= 0 } ?: 0,
                                        onConfirm = { index ->
                                            proxyType = items[index]
                                            handle?.close()
                                        },
                                        onCancel = {
                                            handle?.close()
                                        }
                                    )
                                }
                            )
                        }
                        .padding(vertical = 14.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(
                        text = "代理类型",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(96.dp)
                    )
                    AppText(text = proxyType ?: "请选择", color = MaterialTheme.colorScheme.onSurfaceVariant)
                    Spacer(modifier = Modifier.weight(1f))
                    InfoPopIcon(
                        text = "根据你的代理服务选择 SOCKS5 或 HTTP。",
                        iconSize = 16.dp
                    )
                    Icon(
                        imageVector = Icons.Rounded.KeyboardArrowRight,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 代理主机
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "代理主机",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                        ,modifier = Modifier.width(80.dp))
                    FormField(
                        value = proxyHost,
                        onValueChange = { proxyHost = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        maxLength = 200,
                        type = TextFieldType.Text,
                        borderless = true
                    )
                    HSpacer(6.dp)
                    InfoPopIcon(
                        text = "填写代理节点的服务器地址。",
                        iconSize = 16.dp
                    )
                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    proxyHost = it
                                    context.toastOnUi("已粘贴到主机")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 代理端口
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "代理端口",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp))
                    FormField(
                        value = proxyPort,
                        onValueChange = { proxyPort = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        type = TextFieldType.Number,
                        maxLength = 100,
                        borderless = true
                    )
                    HSpacer(6.dp)
                    InfoPopIcon(
                        text = "端口是连接服务器端口，仅支持数字填写",
                        iconSize = 16.dp
                    )
                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    proxyPort = it
                                    context.toastOnUi("已粘贴到端口")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 代理账号
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "代理账号",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp))
                    FormField(
                        value = proxyAccount,
                        onValueChange = { proxyAccount = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        maxLength = 200,
                        borderless = true
                    )
                    HSpacer(6.dp)
//                    InfoPopIcon(
//                        text = "代理类型：根据你的代理服务选择 HTTP、HTTPS 或 SOCKS5。",
//                        iconSize = 16.dp
//                    )
//                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = "",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    proxyAccount = it
                                    context.toastOnUi("已粘贴到账号")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                // 代理密码
                Row(
                    modifier = Modifier
                        .fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppText(text = "代理密码",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.width(80.dp))
                    FormField(
                        value = proxyPassword,
                        onValueChange = { proxyPassword = it },
                        label = "",
                        modifier = Modifier.weight(1f),
                        placeholder = "请输入",
                        maxLength = 200,
                        type = TextFieldType.Email,
                        borderless = true
                    )
                    HSpacer(6.dp)
//                    InfoPopIcon(
//                        text = "代理类型：根据你的代理服务选择 HTTP、HTTPS 或 SOCKS5。",
//                        iconSize = 16.dp
//                    )
//                    HSpacer(6.dp)
                    Icon(
                        painter = painterResource(id = R.mipmap.ic_stickup),
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                            .size(18.dp)
                            .debouncedClickable {
                                pasteText(context)?.let {
                                    proxyPassword = it
                                    context.toastOnUi("已粘贴到密码")
                                } ?: context.toastOnUi("剪贴板为空或非文本")
                            }
                    )
                }
            }

        }

        Box(
            modifier = Modifier
                .shadow(4.dp)
                .background(Color.White)
                .border(1.dp, color = Color(0xfff2f2f2))
                .padding(start = 32.dp, end = 32.dp, top = 16.dp, bottom = 16.dp + navigationBarHeight),
            contentAlignment = Alignment.Center
        ) {
            Button(
                onClick = {
                    val account = AccountEntry(
                        key = key.account?.key ?: "",
                        accountID = accountId,
                        userId = "",
                        nickname = nickname,
                        password = password,
                        phone = phone,
                        twoFa = twoFa,
                        email = email,
                        emailPassword = emailPassword,
                        ipCountry = ipCountry,
                        cookie = cookie,
                        authCode = key.account?.authCode,
                        type = accountType,
                        platform = platform,
                        tags =  key.account?.tags,
                        proxyChannel =  proxyChannel,
                        proxyType =  proxyType,
                        proxyHost =  proxyHost,
                        proxyPort =  proxyPort,
                        proxyAccount =  proxyAccount,
                        proxyPassword =  proxyPassword,
                        proxyDetect = proxyDetect,
                    )
                    viewModel.onAddOrEditAccount(account)
                          },
                enabled = !uiState.isSave,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp),
                shape = RoundedCornerShape(12.dp)
            ) {
                if (uiState.isSave) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        strokeWidth = 2.dp,
                        color = MaterialTheme.colorScheme.onSecondary
                    )
                    HSpacer(4.dp)
                    Text(
                        text = "保存中...",
                        textAlign = TextAlign.Center,
                        color = MaterialTheme.colorScheme.onSecondary
                    )
                } else Text(text = "保存", textAlign = TextAlign.Center)
            }
        }

    }

}

fun copyText(context:Context,content:String){
    val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clip = ClipData.newPlainText("label", content)
    clipboard.setPrimaryClip(clip)
    context.toastOnUi("复制完成")
}

fun pasteText(context: Context): String? {
    val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clip = clipboard.primaryClip
    if (clip == null || clip.itemCount == 0) return null
    val text = clip.getItemAt(0).coerceToText(context)?.toString()
    return text?.trim()
}

@Composable
fun InfoPopIcon(
    text: String,
    modifier: Modifier = Modifier,
    iconPainter: Painter = painterResource(R.mipmap.ic_proxy_exclamation),
    iconTint: Color = MaterialTheme.colorScheme.onSurfaceVariant,
    iconSize: Dp = 16.dp,
    menuOffset: DpOffset = DpOffset(0.dp, 4.dp),
) {
    var expanded by remember { mutableStateOf(false) }
    Box(modifier = modifier) {
        Icon(
            painter = iconPainter,
            contentDescription = null,
            tint = iconTint,
            modifier = Modifier
                .size(iconSize)
                .debouncedClickable { expanded = true }
        )
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            offset = menuOffset,
            shadowElevation = 0.dp,
            containerColor = Color(0xaa000000)
        ) {
            Box(
                modifier = Modifier
                    .widthIn(min = 160.dp, max = 280.dp)
                    .padding(horizontal = 8.dp)
            ) {
                Text(
                    text = text,
                    style = MaterialTheme.typography.bodySmall,
                    color = Color.White
                )
            }
        }
    }
}